package zack.gateway.core.socket.handlers;

import zack.gateway.core.mapping.HttpStatement;
import zack.gateway.core.socket.BaseHandler;
import zack.gateway.core.session.Configuration;
import zack.gateway.core.socket.agreement.AgreementConstants;
import zack.gateway.core.socket.agreement.GatewayResultMessage;
import zack.gateway.core.socket.agreement.RequestParser;
import zack.gateway.core.socket.agreement.ResponseParser;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.ExecutionException;

/**网络协议处理器，給通道添加属性
 * @author A1793
 */
public class GatewayServerHandler extends BaseHandler<FullHttpRequest> {

    private Logger logger = LoggerFactory.getLogger(this.getClass());
    private final Configuration configuration;

    public GatewayServerHandler(Configuration configuration) {
        this.configuration = configuration;
    }

    @Override
    protected void session(ChannelHandlerContext ctx, Channel channel, FullHttpRequest fullHttpRequest) throws ExecutionException, InterruptedException {

        try{
            //参数处理
            RequestParser requestParser = new RequestParser(fullHttpRequest);
            String uri = requestParser.getUri();
            //获取网关接口映射信息并加入到通道的属性中
            HttpStatement httpStatement = configuration.getHttpStatement(uri);
            channel.attr(AgreementConstants.HTTP_STATEMENT).set(httpStatement);
            //放行到下个处理器
            fullHttpRequest.retain();
            ctx.fireChannelRead(fullHttpRequest);
        }catch (Exception e){
// 4. 封装返回结果
            DefaultFullHttpResponse response = new ResponseParser().parse(GatewayResultMessage.buildError(AgreementConstants.ResponseCode._500.getCode(), "网关协议调用失败！" + e.getMessage()));
            channel.writeAndFlush(response);
        }

    }
}
